public class text {
    public ListNode removeElements(ListNode head, int val) {
        while (head != null && head.val == val) {
            head = head.next;
        }

        if (head == null) {
            return null;
        }
        ListNode cur=head.next;
        ListNode per=head;
        while (cur!=null){
            if(cur.val==val){
                per.next=cur.next;

            }else {

                per=per.next;
            }
            cur=cur.next;
        }
        return head;
    }
    public ListNode reverseList(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }

        ListNode prev = null;
        ListNode current = head;

        while (current != null) {
            ListNode nextTemp = current.next; // 保存下一个节点
            current.next = prev;              // 反转指针方向
            prev = current;                   // 移动prev到当前节点
            current = nextTemp;               // 移动current到下一个节点
        }

        return prev; // 当循环结束时，prev就是新的头节点
    }
    //获取链表倒数第K个节点
    public ListNode lastk(int k,ListNode head){
        ListNode fast=head;
        ListNode slow=head;
        while(k!=1){
            if(null == fast){
                return null;
            }
            fast=fast.next;
            k--;
        }
        while(fast.next!=null){
            fast=fast.next;
            slow=slow.next;
        }
        return slow;
    }
    public ListNode middleNode(ListNode head) {
        //给你单链表的头结点 head ，请你找出并返回链表的中间结点。
        //
        //如果有两个中间结点，则返回第二个中间结点。
        ListNode fast=head;
        ListNode slow=head;
        if(head==null||head.next==null){
            return head;
        }
        while(fast != null && fast.next != null){
            fast=fast.next.next;
            slow=slow.next;
        }
        return slow;
    }

    public class ListNode {
        int val;
        ListNode next;

        ListNode() {

        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
}
